package only.level5.railgun.ysartifactsimulation.handler;

import only.level5.railgun.ysartifactsimulation.publisher.ArtifactInfoPublisher;
import only.level5.railgun.ysartifactsimulation.publisher.HutaoDmgPublisher;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.WebSocketSession;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.concurrent.ConcurrentHashMap;


@Component
public class ReactiveWebSocketHandler implements WebSocketHandler {
    private static final Logger log = LoggerFactory.getLogger(ReactiveWebSocketHandler.class);

    public static ConcurrentHashMap<String, YsArtifactHandler> publisherMap = new ConcurrentHashMap<>();
    @Autowired
    private HutaoDmgPublisher hutaoDmgPublisher;
    @Autowired
    private ArtifactInfoPublisher artifactInfoPublisher;

    @Override
    public Mono<Void> handle(WebSocketSession webSocketSession) {
        URI uri = webSocketSession.getHandshakeInfo().getUri();
        String path = uri.getPath();
        String sessionId = webSocketSession.getId();
        YsArtifactHandler handler = null;
        if (StringUtils.endsWith(path, "dmg")) {
            handler = new YsArtifactHandler(hutaoDmgPublisher);
        } else if (StringUtils.endsWith(path, "artifact")) {
            handler = new YsArtifactHandler(artifactInfoPublisher);
        }
        webSocketSession
                .receive()
                .doOnRequest(a->System.out.println("--Request--"+a))
                .doOnComplete(()->System.out.println("--complete--"))
                .doFinally(signalType -> removeSessionHandle(webSocketSession))
                .subscribe(inMsg -> System.out.println("Received inbound message from client [{}]: {}"+sessionId + inMsg.getPayloadAsText()));
        assert handler != null;
        return handler.handle(webSocketSession);
    }

    public static void removeSessionHandle(WebSocketSession webSocketSession) {
        System.out.println("session {} close "+webSocketSession.getId());
        webSocketSession.close();
    }
}
